<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\CoinLog;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildHostManage;
use App\Model\GuildManage;
use App\Model\HostInfo;
use App\Model\PayOrder;
use App\Model\Stat\StatDaily;
use App\Model\Stat\StatDailyHostInfo;
use App\Model\Stat\StatHostInfoTime;
use App\Model\UserActLog;
use App\Model\UserProfile;
use App\Util\DateUtil;
use App\Util\ToolUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Helper\Helper;

/**
 * 充值排行管理
 */
class PayRankController extends Controller
{
    use ModelForm;

    public function index()
    {
        $content = new Content();
        $content->header('用户充值金额排行');
        $content->description('更新时间：即时');
        $content->body($this->grid());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new PayOrder());
        // $where = [
        // ['status', PayOrder::STATUS_OK],
        // ];
        $status = [PayOrder::STATUS_OK, PayOrder::STATUS_EXTRA];
        $grid->model()->whereIn('status', $status)->select(DB::raw('user_id, SUM(total_amount) AS total_pay'))->groupBy('user_id')->orderBy('total_pay', 'desc');
        $grid->user_id('内部ID')->sortable();
        $grid->userProfile()->user_profile_id('用户ID');
        $grid->userItem()->channel('注册渠道');
        $grid->userProfile()->nick_name('昵称');
        $grid->userProfile()->locate_city('定位城市')->display(function ($data) {
            return ToolUtil::checkInProvince($data, '山东') ? '山东' : '-';
        });
        $grid->userProfile()->birthday('年龄')->display(function ($data) {
            return DateUtil::newDateDiff($data, date('Y-m-d'), 'Y') . ' 岁';
        });
        $grid->userProfile()->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->total_pay('充值总额')->display(function ($data) {
            return round($data / 100, 1);
        })->sortable();
        $grid->userProfile()->updated_at('最新活跃时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        // $grid->footer(function ($query) {
        //     $data = $query->get();
        //     $total = 0;
        //     foreach ($data as $item) $total += $item->total_pay;
        //     return "总计金额：" . round($total / 100, 1);
        // });
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '用户ID');
                $filter->between('userProfile.created_at', '注册时间')->datetime();
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->between('finished_at', '支付时间')->datetime();
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
        });
        return $grid;
    }

    public function icome_index()
    {
        $content = new Content();
        $content->header('女用户收入排行（金币）');
        $content->description('更新时间：30分钟左右');
        $guildHosts = GuildHost::getAllHosts();
        $content->body($this->income_grid($guildHosts));
        return $content;
    }

    protected function income_grid($guildHosts)
    {
        $grid = new Grid(new HostInfo());
        $where = [];
        $grid->model()->where($where)->orderBy('updated_at', 'desc');
        $grid->user_id('内部ID')->sortable();
        $grid->userProfile()->user_profile_id('女用户ID');
//        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
//            return isset($guildHosts[$this->user_id]) ? $guildHosts[$this->user_id] : '';
//        });
        $grid->userProfile()->nick_name('昵称');
        $grid->userProfile()->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->income_total('总收入')->sortable();
        $grid->income_video('视频收入')->sortable();
        $grid->income_gift('普通礼物收入')->sortable();
        $grid->income_msg('私信收入')->sortable();
        $grid->income_voice('语音收入')->sortable();
        $grid->income_sysgift('名义系统礼物收入')->sortable();
        $grid->status('当前身份状态')->display(function ($data) {
            return $data == 1 ? '√' : 'X';
        });
        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '用户ID');
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
        });
        return $grid;
    }

    public function icome_index_time()
    {
        $content = new Content();
        $content->header('女用户收入排行（金币）');
        $content->description('更新时间：每个小时的第5分钟和第35分钟');
        $content->body($this->income_time_grid());
        return $content;
    }

    protected function income_time_grid()
    {
        if (!request()->dt) {
            request()->merge(['dt' => ['start' => date('Y-m-d', strtotime('-1 day')), 'end' => date('Y-m-d', strtotime('-1 day'))]]);
        }

        $dt = request('dt');
        $dt_start = $dt['start'] ?? '';
        $dt_end   = $dt['end'] ?? '';

        $grid = new Grid(new StatDailyHostInfo());
        $where = [];
        $adminId = Admin::user()->id;
        if($adminId == 50 || $adminId == 51){
            $ghId= GuildManage::getGuidIdByGuildUserId($adminId);
            $userIds = GuildHostManage::whereIn('guild_manage_id',$ghId)->pluck('host_user_id')->toArray();
            $grid->model()->where($where)->whereIn('user_id',$userIds)->groupBy('user_id')->orderBy('income_total', 'desc')->select(
                DB::raw(
                    'user_id,
                SUM(income_total) AS income_total,
                SUM(income_video) AS income_video,
                SUM(income_gift) AS income_gift,
                SUM(income_msg) AS income_msg,
                SUM(income_voice) AS income_voice,
                SUM(income_sysgift) AS income_sysgift,
                SUM(income_video_default) AS income_video_default,
                SUM(income_video_match) AS income_video_match,
                SUM(income_video_invite) AS income_video_invite,
                SUM(income_video_discount) AS income_video_discount,
                SUM(income_video_daily_free) AS income_video_daily_free,
                SUM(income_daily_task) AS income_daily_task'
                ));
        }else{
            $grid->model()->where($where)->groupBy('user_id')->orderBy('income_total', 'desc')->select(
                DB::raw(
                    'user_id,
                SUM(income_total) AS income_total,
                SUM(income_video) AS income_video,
                SUM(income_gift) AS income_gift,
                SUM(income_msg) AS income_msg,
                SUM(income_voice) AS income_voice,
                SUM(income_sysgift) AS income_sysgift,
                SUM(income_video_default) AS income_video_default,
                SUM(income_video_match) AS income_video_match,
                SUM(income_video_invite) AS income_video_invite,
                SUM(income_video_discount) AS income_video_discount,
                SUM(income_video_daily_free) AS income_video_daily_free,
                SUM(income_daily_task) AS income_daily_task'
                ));
        }

        $grid->user_id('内部ID')->sortable();
        $grid->userProfile()->user_profile_id('女用户ID');
////        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
////            return isset($guildHosts[$this->user_id]) ? $guildHosts[$this->user_id] : '';
////        });
        $grid->userProfile()->nick_name('昵称');
        $grid->userProfile()->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->income_total('总收入')->sortable();
        $grid->income_video('视频收入')->sortable();
        $grid->income_video_default('常规视频收入')->sortable();
        $grid->income_video_match('随心聊收入')->sortable();
        $grid->income_video_invite('约会视频收入')->sortable();
        $grid->income_video_discount('特惠视频收入')->sortable();
        $grid->income_video_daily_free('天天免费福利视频收入')->sortable();
        $grid->income_gift('普通礼物收入')->sortable();
        $grid->income_msg('私信收入')->sortable();
        $grid->income_voice('语音收入')->sortable();
        $grid->income_sysgift('名义系统礼物收入')->sortable();
        $grid->income_daily_task('每日任务收入')->sortable();
        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('user_id', '内部ID');
                $filter->between('dt', '收入日期')->date();
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
        });

        $grid->footer(function ($query) use ($dt_start, $dt_end) {
            $userId   = request('user_id');

            $where = [];
            if ($userId) {
                $where[] = ['user_id', '=', $userId];
            }

            if ($dt_start) {
                $where[] = ['dt', '>=', $dt_start];
            }

            if ($dt_end) {
                $where[] = ['dt', '<=', $dt_end];
            }

            $staTotal = StatDailyHostInfo::where($where)->select(
                DB::raw(
                    '
                    SUM(income_total) AS income_total,
                    SUM(income_video) AS income_video,
                    SUM(income_gift) AS income_gift,
                    SUM(income_msg) AS income_msg,
                    SUM(income_voice) AS income_voice,
                    SUM(income_sysgift) AS income_sysgift,
                    SUM(income_video_default) AS income_video_default,
                    SUM(income_video_match) AS income_video_match,
                    SUM(income_video_invite) AS income_video_invite,
                    SUM(income_video_discount) AS income_video_discount,
                    SUM(income_video_daily_free) AS income_video_daily_free,
                    SUM(income_daily_task) AS income_daily_task
                '))->first();

            $data = [
                'income_video_default'    => $staTotal['income_video_default'],
                'income_video_match'      => $staTotal['income_video_match'],
                'income_video_invite'     => $staTotal['income_video_invite'],
                'income_video_discount'   => $staTotal['income_video_discount'],
                'income_video_daily_free' => $staTotal['income_video_daily_free'],
                'income_daily_task'       => $staTotal['income_daily_task'],
                'income_total'             => $staTotal['income_total'],
                'income_gift'             => $staTotal['income_gift'],
            ];
            // Log::info(__CLASS__ . "==Start:" . json_encode($start) . "==End:" . json_encode($end) . "==Channel:" . json_encode($channel) . "==" . json_encode($data));
            $adminId = Admin::user()->id;
          if($adminId != 50 && $adminId != 51){
              return '<table class="table custom-data-table data-table">
            <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th>汇总：</th>
                <th>总收入：'.$data['income_total'].'</th>
                <th>常规视频收入: '.$data['income_video_default'].'</th>
                <th>随心聊收入: '.$data['income_video_match'].'</th>
                <th>约会视频收入: '.$data['income_video_invite'].'</th>
                <th>特惠视频收入: '.$data['income_video_discount'].'</th>
                <th>天天免费福利视频收入: '.$data['income_video_daily_free'].'</th>
                <th>每日任务收入: '.$data['income_daily_task'].'</th>
                <th>普通礼物收入: '.$data['income_gift'].'</th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
            </thead></table>';
          }

        });

        return $grid;
    }
}
